package com.wad.expression;

import com.wad.security.LoginUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *
 * 自定义权限注解实现类
 * @author wad
 * @date 2022/11/14 20:40
 * @project JWT_DEMO2
 **/

@Component(value = "ex")
/**
 * Controller中@PreAuthority注解中使用SPEL表达式使用@ex相当于获取容器中bean的名字为ex的对象，然后再调用这个对象中自定义的权限方法
 * example：@PreAuthority("@ex.hasAuthority('system:dept:list')")
 */
public class SecurityExpressionRoot  {

    public boolean hasAuthority(String authority){
//        获取当前用户的权限
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser principal = (LoginUser) authentication.getPrincipal();
        List<String> permissions = principal.getPermissions();
//        判断用户权限集合中是否存在authority
        return permissions.contains(authority);
    }
}
